import {
  getInspectSubItemByPage,
  addInspectSubItem,
  updateInspectSubItem,
  delInspectSubItem,
  exportInspectSubItem,
} from '@/services/device/inspectSubItem';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Col, Form, Input, message, Modal, Row, Tree } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
const InspectSubItem: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const [inspectId, setInspectId] = useState();
  const ref = useRef(null);
  useEffect(() => {
    setInspectId(props.inspectId);
  });
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '检查描述',
      dataIndex: 'checkDesc',
      align: 'center',
      sorter: true,

      ellipsis: true,
    },
    {
      title: '检查项目',
      dataIndex: 'checkItem',
      align: 'center',
      sorter: true,

      ellipsis: true,
    },
    {
      title: '唯一标识',
      dataIndex: 'identification',
      search: false,
      hideInTable: true,
      align: 'center',
      sorter: true,
    },
    {
      title: '巡检计划编号',
      dataIndex: 'inspectID',
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '是否需要附件',
    //   dataIndex: 'isAttached',
    //   search: false,
    //   align: 'center',
    //   sorter: true,

    //   render: (text: any) => {
    //     return <div>{text === 'true' ? '是' : '否'}</div>;
    //   },
    // },
    {
      title: '是否有效',
      dataIndex: 'isValid',
      search: false,
      hideInTable: true,
      align: 'center',
      sorter: true,

      valueType: 'select',
    },
    {
      title: '备注',
      dataIndex: 'notes',
      search: false,
      align: 'center',
      sorter: true,
    },
    {
      title: '顺序编号',
      dataIndex: 'sequence',
      search: false,
      hideInTable: true,
      align: 'center',
      sorter: true,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      hideInTable: true,
      align: 'center',
      sorter: true,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      search: false,
      hideInTable: true,
      align: 'center',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',

      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(false);
            setFormTitle('编辑');
            form.setFieldsValue({
              checkDesc: record.checkDesc,
              checkItem: record.checkItem,
              identification: record.identification,
              inspectid: inspectId,
              isAttached: record.isAttached,
              isValid: record.isValid,
              notes: record.notes,
              sequence: record.sequence,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delInspectSubItem({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = (values: any) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      try {
        console.log(values);
        const result = addInspectSubItem(values);
        console.log(result);
        result.then((res) => {
          if (res != null) {
            message.success('添加成功');
          }
        });
      } catch (error) {
        console.log('error', error);
        message.error(error);
      }
    } else {
      updateInspectSubItem(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current.reload();
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="巡检计划子项查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportInspectSubItem({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `InspectSubItem.xlsx`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const paramsFilter = { ...params, InspectID: inspectId };
          const sorters = sortTran(sort);
          const filters = filterTran(paramsFilter);
          // sorters.forEach((item: any) => {
          //   item.field = item.field[0].toUpperCase() + item.field.subString(1);
          // });
          console.log(filters);
          filters.map((item: any) => {
            const newField = item.field[0].toUpperCase() + item.field.substring(1);
            item.field = newField;
          });
          sorters.map((item: any) => {
            const newField = item.field[0].toUpperCase() + item.field.substring(1);
            item.field = newField;
          });
          const result = await getInspectSubItemByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1500, y: 350 }}
        rowSelection={{}}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
        initialValues={{
          identification: '巡检计划子项',
          isValid: true,
          inspectID: inspectId,
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="identification"
          label="唯一标识"
          rules={[{ required: true, message: '请输入唯一标识!' }]}
          disabled={createOrUpdate}
          hidden={true}
        />

        <ProFormText
          name="inspectID"
          label="巡检计划编号"
          rules={[{ required: true, message: '请输入巡检计划编号!' }]}
          disabled={true}
        />

        {/* <Col span={12}>
            <ProFormSelect
              name="isAttached"
              label="是否需要附件"
              rules={[{ required: true, message: '请选择是否需要附件!' }]}
              disabled={createOrUpdate}
              options={[
                { label: '是', value: true },
                { label: '否', value: false },
              ]}
            />
          </Col> */}

        <ProFormText
          name="checkItem"
          label="检查项目"
          rules={[{ required: true, message: '请输入检查项目!' }]}
          disabled={createOrUpdate}
        />
        <ProFormTextArea
          name="checkDesc"
          label="检查描述"
          rules={[{ required: true, message: '请输入检查描述!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="isValid"
          label="是否有效"
          rules={[{ required: true, message: '请选择是否有效!' }]}
          disabled={createOrUpdate}
          hidden={true}
        />
        <ProFormTextArea name="notes" label="备注" disabled={createOrUpdate} />
        <ProFormText name="sequence" label="顺序编号" disabled={createOrUpdate} hidden={true} />
      </ModalForm>
    </PageHeaderWrapper>
  );
};
export default InspectSubItem;
